package my.http;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.stream.FileImageOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 模拟浏览器请求的工具类,用于调用接口,参数是json数据
 * 
 * @author guojian
 * 
 */
public class HttpClientUtil {

	private static BasicCookieStore cookieStore = new BasicCookieStore();
	private static RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
	private static CloseableHttpClient commonHttpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

	private static final Log log = LogFactory.getLog(HttpClientUtil.class);

	public static String sendPost(String url, List<NameValuePair> nvps) {
		HttpPost httpPost = new HttpPost(url);
		setCommonHeads(httpPost);
		String responseMessage = "";
		try {
			if (nvps != null) {
				httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			}
			CloseableHttpResponse response = commonHttpclient.execute(httpPost);
			responseMessage = EntityUtils.toString(response.getEntity(), "UTF-8");
			log.info("==============sendPost: ================ " + responseMessage);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responseMessage;
	}

	public static String sendGet(String url) {
		HttpGet httpGet = new HttpGet(url);
		setCommonHeads(httpGet);
		String responseMessage = "";
		try {
			CloseableHttpResponse response = commonHttpclient.execute(httpGet);
			HttpEntity responseEntity = response.getEntity();
			String responseContentType = ContentType.getOrDefault(responseEntity).toString();
			if (responseContentType.contains("image")) {
				File imageFile = new File("G:/郭剑资源文件/image/" + UUID.randomUUID() + ".jpg");
				FileImageOutputStream imageOut = new FileImageOutputStream(imageFile);
				imageOut.write(EntityUtils.toByteArray(responseEntity));
				imageOut.flush();
				imageOut.close();
				responseMessage = imageFile.getAbsolutePath();
			} else {
				responseMessage = EntityUtils.toString(responseEntity, "UTF-8");
			}
			log.info("=========responseContentType==============: " + responseContentType);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responseMessage;
	}

	private static void setCommonHeads(HttpUriRequest request) {
		List<Header> headers = new ArrayList<Header>();
		headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36"));
		headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
		headers.add(new BasicHeader("Connection", "keep-alive"));
		headers.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
		Header[] headersObject = new Header[headers.size()];
		request.setHeaders(headers.toArray(headersObject));
	}

	public static String loginWWW(String url, Map<String, String> nameValues) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (nameValues != null) {
			for (String name : nameValues.keySet()) {
				nvps.add(new BasicNameValuePair(name, nameValues.get(name)));
			}
		}
		return HttpClientUtil.sendPost(url, nvps);
	}

	public static void getYZM(String url) {
		sendGet(url);
	}

	public static void loginOschina() {
		Map<String, String> nameValues = new HashMap<String, String>();
		nameValues.put("email", "709155823@qq.com");
		nameValues.put("pwd", "98253c8941959d240b1e5ea353e1e4b3d96514ef");
		nameValues.put("save_login", "1");
		nameValues.put("verifyCode", "");
		loginWWW("https://www.oschina.net/action/user/hash_login", nameValues);
	}

	private static void testEventDynmic() {
		// HttpClientUtil.getYZM("http://www.jobbole.com/captcha.php?r=0.34834744468016265");
		// Scanner sin = new Scanner(System.in);
		// System.out.println(sin.nextLine());

		Map<String, String> namevalues = new HashMap<String, String>();
		namevalues.put("eventId", "guojian33333333333");
		// namevalues.put("user_login", "guojian111");
		// namevalues.put("display_name", "12121");
		// namevalues.put("user_email", "70915824@qq.com");
		// namevalues.put("verify_code", sin.nextLine());
		// HttpClientUtil.loginWWW("http://www.jobbole.com/wp-admin/admin-ajax.php",
		// namevalues);

		// HttpClientUtil.loginOschina();
		// HttpClientUtil.sendGet("https://my.oschina.net/chaoren8/admin/profile");

		// System.out.println(HttpClientUtil.sendGet("http://avatar.csdn.net/3/5/F/1_huang9012.jpg"));
		HttpClientUtil.loginWWW("http://localhost:8080/futianweb/servlet/uploadEventDynamicServlet", namevalues);

		HttpPost httpPost = new HttpPost("http://localhost:8080/futianweb/servlet/uploadEventDynamicServlet");
		setCommonHeads(httpPost);

		HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("file1", new File("F:/mm.jpg"), ContentType.DEFAULT_BINARY, "").build();
		httpPost.setEntity(entity);
		try {
			CloseableHttpResponse response = commonHttpclient.execute(httpPost);
			System.out.println(EntityUtils.toString(response.getEntity()));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		/*
		 * Map<String, String> namevalues = new HashMap<String, String>();
		 * namevalues.put("page", "1"); namevalues.put("index", "10"); String
		 * res = loginWWW(
		 * "http://191.0.6.10:8800/lgywsoft/predict/getAlertInfo.action",
		 * namevalues); JSONObject object = new JSONObject();
		 * object.element("all", res); System.out.println(object.toString());
		 */
		//		Map<String, String> namevalues = new HashMap<String, String>();
		//		namevalues.put("eventLevel", "三级");
		//		namevalues.put("eventTypeCode", "11B03");
		//		loginWWW("http://191.0.6.10:8800/lgywsoft/predict/getAlertPlan.action", namevalues);

		System.out.println(sendGet("http://www.szmb.gov.cn/"));

		//URL urlOfClass = HttpClientUtil.class.getClassLoader().getResource("org/slf4j/spi/LocationAwareLogger.class");
		//System.out.println(urlOfClass);

	}

}
